from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from exercise.models import Exercise
from exercise.serializers import ExerciseSerializer


# Create your views here.
class ExerciseList(APIView):
    #  列出数据库中所有的题目，或者向数据库新增题目
    def get(self, request):
        exercises = Exercise.objects.all()
        s = ExerciseSerializer(exercises, many=True)
        return Response(s.data)

    def post(self, request):
        s = ExerciseSerializer(data=self.request.data)
        if s.is_valid():
            s.save(creator=self.request.user)
            return Response(s.data, status=status.HTTP_201_CREATED)
        return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)
